package org.nbk.calculator;

import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.Button;
import android.widget.TextView;

public class CalculatorActivity extends Activity {
	
	//instance variables
	private CalculatorEngine myEngine;
	
	//Android widgets
	private TextView calculatorDisplay;
	
	//constants
	//Distance of the 0 character on the ASCII table
	//from the beginning of the table
	//private static final int DISTANCE_FROM_ZERO = 48;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LayoutInflater inflater=getLayoutInflater();
        View mainView = inflater.inflate(R.layout.main, null);
        mainView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
			@Override
			public void onGlobalLayout() {
		        calculatorDisplay=(TextView)findViewById(R.id.CalculatorField);
			}
		});
        myEngine = new CalculatorEngine();
        setContentView(mainView);
    }
    
    public void buttonClicked(View v) {
    	
    	Button b = (Button) v;
    	String buttonText = (String) b.getText();
    	char firstChar = buttonText.charAt(0);
    	String result = "";
    	boolean errorFound = false;
    	
    	//Check if number button was clicked
    	if(firstChar >= '0' && firstChar <= '9') {
			try {
				myEngine.digit(firstChar);
			} catch (OutOfBoundsException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		//Check if one of the clear buttons was clicked
    	} else if(firstChar == 'C' || firstChar == 'B') {
    		if(buttonText.equals("C")) myEngine.clear();
    		else if(buttonText.equals("CE")) myEngine.clearEntry();
    		else if(buttonText.equals("Bksp")) myEngine.backspace();
    	} else {
    		switch(firstChar) {
    		case '+':
    			myEngine.add();
    			break;
    		case '-':
    			myEngine.subtract();
    			break;
    		case 'X':
    			myEngine.multiply();
    			break;
    		case '/':
    			myEngine.divide();
    			break;
    		case '^':
    			myEngine.exponent();
    			break;
    		case '.':
    			//Do nothing if exception is thrown
    			try {
					myEngine.decimal();
				} catch (InvalidOperationException e) {}
    			break;
    		case '=':
    			try {
					result = myEngine.compute();
				} catch (InvalidOperationException e) {
					myEngine.clear();
					calculatorDisplay.setText("Error: operation");
					errorFound=true;
				}
    			break;
    		default:
    			calculatorDisplay.setText("Error: button");
    			errorFound=true;
    		}
    	}
    	
    	//Update the display unless an error occurred.
    	if(!errorFound) updateDisplay(result);
    }
    
    /*
     * Updates the calculator display.
     * If a computation was done and a result found, that result is displayed.
     * Otherwise, the current value is displayed.
     */
    private void updateDisplay(String result) {
    	if(result.length() == 0) {
    		String curVal = myEngine.getValue();
    		//CalculatorEngine will use an empty string for a value of 0
    		if(curVal.length() == 0) calculatorDisplay.setText("0");
    		else calculatorDisplay.setText(curVal);
    	}
    	else calculatorDisplay.setText(result);
    }
}